<template>
  <!-- 完全保持原有结构 -->
  <div class="detail-box">
    <AdvertisementO />
    <div class="detail-context">
      <div class="detail-left">
        <DetailTilte 
          :newsTitle="detailData.newsTitle" 
          :newsTime="detailData.newsTime" 
          :publisherName="detailData.publisherName" 
          :userLocation="detailData.userLocation" 
        />
        <div class="detail-body">
          <div class="post-top">
            <PostTop :follower="detailData.follower" :totalComment="totalComment" />
          </div>
          <div class="text-comment">
            <PostText :content="detailData.newsDetailBody" />
            <Comment :news_id="news_id" @total-comment="handleTotalComment" />
          </div>
        </div>
      </div>
      
      <!-- 仅修改这个区域 -->
      <div class="detail-right">
        <PublisherInfo 
          :publisherName="detailData.publisherName" 
          :userFans="detailData.userFans" 
          :userArticles="detailData.userArticles"
          :userProfile="detailData.userProfile"
        />
        <PublishHistory :publisherName="detailData.publisherName" />
        <div class="news-recommend" ref="stickyRecommend">
          <NewsRecommend />
          <NewsRecommend />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import AdvertisementO from "../main-components/advertisement.vue";
import DetailTilte from "./DetailTitle.vue";
import PostTop from "./PostTop.vue";
import PostText from "./PostText.vue";
import PublisherInfo from "./PublisherInfo.vue";
import PublishHistory from "./PublishHistory.vue";
import NewsRecommend from "./NewsRecommend.vue";
import Comment from "./Comment.vue";

export default {
  name: "detail",
  props: ['news_id'],
  components: {
    AdvertisementO,
    DetailTilte,
    PostTop,
    PostText,
    PublisherInfo,
    PublishHistory,
    NewsRecommend,
    Comment,
  },
  data() {
    return {
      placeholder: null,
      scrollListener: null,
      resizeListener: null,
      totalComment: 0,
      detailData: {
        newsTitle: "",
        newsTime: "",
        publisherName: "",
        follower: "",
        category: "",
        keywords: "",
        newsDetailBody: "",
        userLocation: "",
        userArticles: "",
        userFans: "",
        userProfile: "",
        userPic: "",
      }
    };
  },
  mounted() {
    this.scrollToTop()
    console.log("新闻ID（通过props）:", this.news_id);
    this.getDetailInfo()
    this.initSticky();
    this.resizeListener = () => this.initSticky();
    window.addEventListener("resize", this.resizeListener);
  },
  beforeDestroy() {
    this.cleanup();
  },
  methods: {
    initSticky() {
      this.cleanup(); // 先清除旧的监听和占位元素

      const recommend = this.$refs.stickyRecommend;
      if (!recommend) return;

      // 添加过渡效果
      recommend.style.transition = "all 0.3s ease";

      // 创建占位元素
      this.placeholder = document.createElement("div");
      this.placeholder.style.display = "none";
      this.placeholder.style.height = `${recommend.offsetHeight}px`;
      this.placeholder.style.transition = "all 1s ease"; // 占位元素也添加过渡
      recommend.parentNode.insertBefore(this.placeholder, recommend);

      // 初始化位置数据
      const stickyOffset = 55; // 距离顶部55px
      const triggerOffset = 900;
      const originalOffset = recommend.offsetTop;
      const recommendWidth = recommend.offsetWidth;

      // 滚动事件处理
      this.scrollListener = () => {
        if (window.innerWidth <= 992) {
          // 小屏幕禁用sticky
          recommend.style.position = "";
          this.placeholder.style.display = "none";
          return;
        }

        // 修改条件：同时满足两个条件
        if (window.pageYOffset > triggerOffset && window.pageYOffset > originalOffset - stickyOffset) {
          // 进入sticky状态
          recommend.style.position = "fixed";
          recommend.style.top = `${stickyOffset}px`;
          recommend.style.width = `${recommendWidth}px`;
          this.placeholder.style.display = "block";
        } else {
          // 普通状态
          recommend.style.position = "";
          this.placeholder.style.display = "none";
        }
      };

      window.addEventListener("scroll", this.scrollListener);
      this.scrollListener(); // 立即执行一次初始化
    },
    cleanup() {
      if (this.scrollListener) {
        window.removeEventListener("scroll", this.scrollListener);
      }
      if (this.placeholder && this.placeholder.parentNode) {
        this.placeholder.parentNode.removeChild(this.placeholder);
      }
    },
    getDetailInfo() {
      this.$api.serviceNews.post('api/news/newsDetail', {"newsId": this.news_id}, {
        headers: {
          'Content-Type': 'application/json'
        }
      })
      .then(response => {
        if (response.data.code == 200){
          console.log(response.data.data);
          this.detailData = response.data.data
          console.log(this.detailData);
        }
      })
      .catch(error => {
        console.error('失败', error);
      });
    },
    handleTotalComment(totalComment) {
      this.totalComment = totalComment;
    },
    scrollToTop() {
      window.scrollTo(0, 0)
    }
  },
};
</script>

<style scoped>
/* 保持其他所有样式完全不变 */
.detail-box {
  display: inline-flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.detail-context {
  margin-top: 30px;
  display: inline-flex;
  align-items: flex-start;
  gap: 42px;
}
.detail-left {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
}
.detail-body {
  margin-top: 30px;
  display: inline-flex;
  justify-content: space-between;
  align-items: flex-start;
}
.text-comment {
  margin-left: 30px;
  display: inline-flex;
  flex-direction: column;
  align-items: flex-start;
}
.detail-right {
  display: inline-flex;
  flex-direction: column;
  align-items: start;
}

/* 仅修改.news-recommend的样式 */
.news-recommend {
  display: inline-flex;
  flex-direction: column;
  align-items: start;
  transition: top 0.2s ease; /* 添加平滑过渡 */
}

/* 新增：固定post-top在左侧 */
.post-top {
  position: sticky;
  top: 70px; /* 可以根据需要调整距离顶部的距离 */
  align-self: flex-start; /* 保持左对齐 */
}
</style>